package com.rainfull.ui;


import java.util.ArrayList;
import java.util.HashMap;

import com.rainfull.core.Config;
import com.rainfull.core.RAPItemInfo;
import com.rainfull.core.RNetworkProcess;
import com.rainfull.core.RUploadApResult;
import com.rainfull.core.RUserInfo;
import com.rainfull.ui.RUIApList;
import com.rainfull.util.HttpUtil;
import com.rainfull.util.json.JSONArray;
import com.rainfull.util.json.JSONObject;

import android.app.ActivityGroup;  
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.LocalActivityManager;  
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;  
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Color;
import android.net.wifi.ScanResult;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;  
import android.os.Handler;
import android.text.TextPaint;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;  
import android.view.WindowManager;
import android.view.View.OnClickListener;  
import android.view.inputmethod.InputMethodManager;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.LinearLayout.LayoutParams;

public class main extends ActivityGroup implements OnClickListener {  
    private LinearLayout m_scrollView = null;
    private int[] m_IdTabList = {R.id.main_ll_tab1, R.id.main_ll_tab2, R.id.main_ll_tab3};
    private java.lang.Class[] m_BtnClassList = {RUIApList.class, RUIGMap.class, RUIAccount.class};
    private int[] m_TexList = {R.id.main_text_static_ap, R.id.main_text_static_map, R.id.main_text_static_account};
    private LocalActivityManager mActivityManager = null;     
    private int m_nCurrTabIndex = -1;
    private long m_nTime = 0;
    public RUserInfo m_userInfo = new RUserInfo();
    public HashMap<String, String> m_apPwdInfo = new HashMap<String, String>();
    public ArrayList<HashMap<String, Object>> m_aplist = new ArrayList<HashMap<String, Object>>();
    public String m_strImei = "";
    /*
     * 获取屏幕宽度
     */
    public int getScreenWidth()
    {
    	WindowManager manager = getWindowManager();
        int width = manager.getDefaultDisplay().getWidth();
        return width;
    }
    /*
     * 后退按键处理
     */
    public boolean onKeyDown(int keyCode, KeyEvent event) 
    {
        if (keyCode == KeyEvent.KEYCODE_BACK) 
        {
        	if (m_nTime != 0 && System.currentTimeMillis() - m_nTime < 2000)
        		System.exit(0);
        	else
        	{
        		m_nTime = System.currentTimeMillis();
        		Toast.makeText(main.this, "再点一次即可关闭该程序", Toast.LENGTH_LONG).show();
        	}
        	
        }
        return false;
    }
    /*
     * 隐藏键盘
     */
    public void showKeyBoard(View view, boolean show)
    {
    	InputMethodManager imm = ((InputMethodManager)getSystemService(INPUT_METHOD_SERVICE));
        if (view != null && view.getWindowToken() != null)
        {
        	if (show == true)
        		imm.hideSoftInputFromWindow(view.getWindowToken(), 1);
        	else
        		imm.showSoftInputFromInputMethod(view.getWindowToken(), 0);
        }
        else
        	imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, InputMethodManager.HIDE_NOT_ALWAYS);           
    }
    @Override 
	public boolean onOptionsItemSelected(MenuItem item)
	{
		super.onOptionsItemSelected(item);
		int nItemId = item.getItemId();
		if (nItemId == 1)//关于
		{
			String strMsg = "版本号:"+getText(R.string.app_ver).toString()+"\r\n新浪腾讯微博：@无线快捕\r\n邮箱:joinwifi@gmail.com";
			new AlertDialog.Builder(main.this).
			setTitle(getText(R.string.app_about_title).toString()).
			setMessage(strMsg)
			.show();
		}
		else if(nItemId == 2) //问题反馈
		{
			Intent intent = new Intent(Intent.ACTION_SEND);
			String[] recipients = new String[]{"joinwifi@gmail.com", "",};
			intent.putExtra(android.content.Intent.EXTRA_EMAIL, recipients); //设置收件人
			intent.putExtra("subject", "无线快捕V"+getText(R.string.app_ver).toString()+"问题反馈"); //主题
			String strBody = "\r\n\r\n\r\n\r\n//以下信息是您的手机基本信息，" +
							"不涉及个人隐私，并有助于我们跟踪问题原因所在。";
			strBody += "\r\nModel:"+Build.MODEL; //手机型号 htc desire
			strBody += "\r\nAPI:"+Build.VERSION.SDK; //apilevel
			strBody += "\r\nDevice:"+Build.DEVICE;
			strBody += "\r\nIMEI:"+m_strImei;
			strBody += "\r\nMac:";
			for(int i=0; i< m_aplist.size(); i++)
			{	        		        		
				ScanResult scanHaveFind = (ScanResult)m_aplist.get(i).get("scanResult");
				if (scanHaveFind != null)
				{
					strBody += scanHaveFind.BSSID+ "\r\n";
				}
			}			
			intent.putExtra("body", strBody); //正文
			intent.setType("text/plain");
			  //startActivity(Intent.createChooser(intent,getResources().getString(R.string.str_message)));
			startActivity(intent); //调用系统的mail客户端进行发送
		}
		else if(nItemId == 3) //刷新无线列表
		{
			
		}
		return true;
	}
	
    @Override 
    public boolean onCreateOptionsMenu(Menu menu) 
    { 
        int groupId = 0; 
        int menuItemOrder = Menu.NONE; 

    	menu.add(groupId, 1, menuItemOrder, "关于").setIcon(getResources().getDrawable(R.drawable.about));    	
    	
    	menu.add(groupId, 2, menuItemOrder, "问题反馈").setIcon(getResources().getDrawable(R.drawable.question));

    	menu.add(groupId, 3, menuItemOrder, "刷新无线列表").setIcon(getResources().getDrawable(R.drawable.refresh));

    	menu.add(groupId, 4, menuItemOrder, "升级").setIcon(getResources().getDrawable(R.drawable.update));
    	
    	return true;
    }
    @Override  
    public void onCreate(Bundle savedInstanceState) 
    {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.main); 
        //显示预加载框
        startActivity(new Intent(getApplication(),RUISplash.class));
        //初始化使用次数
        int nWidth = getScreenWidth();
        m_scrollView = (LinearLayout) findViewById(R.id.containerBody);
        m_scrollView.setLayoutParams(new LayoutParams(nWidth, LayoutParams.FILL_PARENT));
        //设置tab宽度, 设置监听器
        LinearLayout ly = null;
        int nTabWidth = 0;
        for(int i = 0; i < m_IdTabList.length; i++)
        {        
        	nTabWidth = nWidth / m_IdTabList.length;
        	ly = (LinearLayout)findViewById(m_IdTabList[i]);
        	ly.setLayoutParams(new LayoutParams(nTabWidth, 80));
        	ly.setOnClickListener(this);
        }  
        
   	    mActivityManager = getLocalActivityManager();     	 
   	    new RUpoladApInfoTimer().execute(null);  
   	    

        Handler preLoad = new Handler();
        preLoad.postDelayed(new preLoadHandle(), 500);
    }
    class preLoadHandle implements Runnable
    {
        public void run() 
        {        	
    		showTab(2);	 //账号
    		showTab(1);  //地图
    		showTab(0);  //热点
        }
    }
    //监听点击事件
    public void onClick(View v) 
    {
    	int nClickId = v.getId();
    	for(int i = 0; i < m_IdTabList.length; i++)
	   	{
    		if (nClickId == m_IdTabList[i])
	   		{
    			m_nCurrTabIndex = i;
    			showTab(i);
    			break;
	   		}
	   	}
    }
    
    private void showTabView(java.lang.Class classInfo)
    {
    	Intent newIntent = new Intent(this, classInfo);
		newIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
		View newView = mActivityManager.startActivity(classInfo.getName(),  
			    new Intent(this, classInfo)).getDecorView();
		m_scrollView.removeAllViews();
		m_scrollView.addView(newView);
    }
    
    public void changeTabView(java.lang.Class orgClassInfo, java.lang.Class classInfo)
    {
    	for (int i = 0; i < m_BtnClassList.length; i++)
    	{
    		if (m_BtnClassList[i].equals(orgClassInfo) == true)
    		{    			
    			m_BtnClassList[i] = classInfo;
    				
    			if (i == m_nCurrTabIndex)
    			{    		
    				showTabView(classInfo);        			
    			}    			
    			break;
    		}
    	}
    }
    
    private void showTab(int nIndex)
    {
    	m_nCurrTabIndex = nIndex;
    	m_scrollView.removeAllViews();
    	LinearLayout ly = null;
	   	for(int i = 0; i < m_IdTabList.length; i++)
	   	{
	   		//设置tab的text颜色
	    	TextView textView = (TextView)findViewById(m_TexList[i]);
	    	//中文使用以下方法加粗
	    	TextPaint tp = textView.getPaint();
	    	tp.setFakeBoldText(true);
	    	if (i == m_nCurrTabIndex)
	    		textView.setTextColor(0xFF4BA1EB);
	    	else
	    		textView.setTextColor(Color.WHITE);
	    	
	    	getLocalActivityManager();
	   		ly = (LinearLayout)findViewById(m_IdTabList[i]);
	   		if (nIndex == i)
	   		{
	   			java.lang.Class classInfo = m_BtnClassList[i];
	   			ly.setBackgroundResource(R.drawable.tab);
	   			Intent newIntent = new Intent(this, m_BtnClassList[i]);
    			newIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
    			View newView = mActivityManager.startActivity(m_BtnClassList[i].getName(),  
    				    new Intent(this, m_BtnClassList[i])).getDecorView();
    			//有可能start的时候已经变换了
    			if (classInfo.equals(m_BtnClassList[i]) == true)
    				m_scrollView.addView(newView);	   		 			
	   		}
	   		else
	   			ly.setBackgroundResource(0);	   		
	   	}
    }
    /*
     * 用户是否登录
     */
    public int IsUserLogin()
	{
    	if (m_userInfo.getUserName().length() <= 0)
    		return 0;
    	else
    		return 1;
	}
    public void UserExit()
	{
    	m_userInfo = new RUserInfo();
	}
    /*
     * 获取剩余使用次数
     */
    public int getUserScore()
    {
    	if (IsUserLogin() == 1)
    		return m_userInfo.getScore();
    	else
    	{
    		int nInitCount = 10;
    		SharedPreferences spUser = getSharedPreferences("com.rainfull.user", MODE_PRIVATE);
    		int nScore = spUser.getInt("left_count", nInitCount);
    		//修复bug
    		if (nScore > 1000)
    			nScore = 10;
    		if (nScore == 10)
    		{
    			Editor edit = spUser.edit();
    			edit.putInt("left_count", nInitCount);
    			edit.commit();
    		}
    		return spUser.getInt("left_count", nInitCount);
    	}
    }
    /*
     * 减少剩余使用次数
     */
    public boolean addUserScore(int nCount)
    {
    	if (IsUserLogin() == 1)
    		m_userInfo.subScore(nCount);
    	else
    	{
    		int nCurrCount = getUserScore();
	    	if (nCurrCount < nCount)
	    	{
	    		return false;
	    	}    	
	    	nCurrCount = nCurrCount + nCount;
	    	m_userInfo.seLeftCount(nCurrCount);
	    	SharedPreferences spUser = getSharedPreferences("com.rainfull.user", MODE_PRIVATE);
	    	Editor edit = spUser.edit();
	    	edit.putInt("left_count", nCurrCount);
	    	edit.commit();
    	}
    	return true;
    }
    
    public void saveUserInfo()
    {
    	SharedPreferences spUser = getSharedPreferences("com.rainfull.user", MODE_PRIVATE);
    	Editor edit = spUser.edit();
    	edit.putString("user_name", m_userInfo.getUserName());
    	edit.putString("token", m_userInfo.getToken());
    	edit.putInt("score", m_userInfo.getScore());
    	edit.commit();
    }
    
    public RUserInfo GetUserInfoFromStorage()
    {
    	RUserInfo userInfo = new RUserInfo();
    	getUserScore();
    	SharedPreferences spUser = getSharedPreferences("com.rainfull.user", MODE_PRIVATE);    	
    	userInfo.setUserName(spUser.getString("user_name", ""));
    	userInfo.setToken(spUser.getString("token", ""));
    	userInfo.setScore(spUser.getInt("score", 0));
    	return userInfo;
    }
    
	public String getApPwd(String strSSID)
	{
		String strRet = "";
		return strRet;
	}
	 /** 
     * 提示退出系统 
     * @param context 
     * @return 
     */  
     public Dialog ExitDialog(Context context) 
     {  
        AlertDialog.Builder builder = new AlertDialog.Builder(context);  
        builder.setIcon(R.drawable.icon);  
        builder.setTitle("无线快捕");  
        builder.setMessage("确定要退出程序吗?");  
        builder.setPositiveButton("确定",  
                new DialogInterface.OnClickListener() {  
                    public void onClick(DialogInterface dialog, int whichButton) {           
                        finish();  
                    }  
                });  
        builder.setNegativeButton("取消",  
                new DialogInterface.OnClickListener() {  
                    public void onClick(DialogInterface dialog, int whichButton) {  
                    }  
                });  
        return builder.create();  
    }
     
     public void saveUploadFailedApInfo(String strUrlInfo)
     {
     	SharedPreferences spUser = getSharedPreferences("com.rainfull.user", MODE_PRIVATE);
     	Editor edit = spUser.edit();
     	String strApInfo = spUser.getString("ap_info", "");
     	try
     	{
     		JSONArray objArray = new JSONArray();
     		if (strApInfo.length() > 0)
     			objArray = new JSONArray(strApInfo);
     		objArray.put(strUrlInfo);
     		String strRet = objArray.toString();
     		edit.putString("ap_info", strRet);    		
     	}
     	catch(Exception e)
     	{
     		edit.putString("ap_info", "");	//出现异常，可能以前保存数据有问题，清除先    		
     	}
     	edit.commit();
     }   
   //后台上传账号密码信息
 	public class RUpoladApInfoTimer extends AsyncTask
 	{
 		@Override
 		protected Object doInBackground(Object... param) 
 		{ 			
 			while(true)
 			{ 		
 				SharedPreferences spUser = getSharedPreferences("com.rainfull.user", MODE_PRIVATE);
				Editor edit = spUser.edit();	 		     	
 				try
 				{
 					String strApInfo = spUser.getString("ap_info", "");
 	 		     	JSONArray objArray = new JSONArray();
 	 	     		if (strApInfo.length() > 0)
 	 	     			objArray = new JSONArray(strApInfo);
 	 	     		if (objArray.length() > 0)
 	 	     		{
 	 	     			JSONArray objArray2 = new JSONArray();
	 	 	     		if (strApInfo.length() > 0)
	 	 	     			objArray2 = new JSONArray(strApInfo);
	 	 	     		for(int i = objArray.length() - 1; i >= 0 ; i--)
	 	 	     		{
	 	 	     			String strData = objArray.get(i).toString();
	 	 	     			String strRet = HttpUtil.PostInfo(Config.strUrlUploadApInfo, strData);
	 	 	     			if (strRet.length() > 0)
	 	 	     			{
	 	 	     				objArray2.remove(i);
	 	 	     			}
	 	 	     		}
	 	 	     		edit.putString("ap_info", objArray2.toString());
	 	 	     		edit.commit();
 	 	     		}
 					Thread.sleep(1000);
 				}
 				catch(Exception e)
 				{
 					edit.putString("ap_info", "");
 	 	     		edit.commit();
 					
 				}
 			}
 		}
 	}
}